﻿using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Events;

#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UI;
#endif

namespace Jinndev {

    public class CustomScrollRect : ScrollRect {

        public event UnityAction<PointerEventData> customOnScroll;

        public bool preventScroll;

        public override void OnScroll(PointerEventData data) {
            if (!preventScroll) {
                base.OnScroll(data);
            }
            customOnScroll?.Invoke(data);
        }

    }

#if UNITY_EDITOR
    [CustomEditor(typeof(CustomScrollRect))]
    public class CustomScrollRectEditor : ScrollRectEditor {

        [MenuItem("CONTEXT/ScrollRect/Convert To CustomScrollRect")]
        public static void ConvertToCustomScrollRect(MenuCommand command) {
            ScrollRect scrollRect = command.context as ScrollRect;
            GameObject gameObject = scrollRect.gameObject;

            RectTransform content = scrollRect.content;
            bool horizontal = scrollRect.horizontal;
            bool vertical = scrollRect.vertical;
            var movementType = scrollRect.movementType;
            float elasticity = scrollRect.elasticity;
            bool inertia = scrollRect.inertia;
            float decelerationRate = scrollRect.decelerationRate;
            RectTransform viewport = scrollRect.viewport;
            Scrollbar horizontalScrollbar = scrollRect.horizontalScrollbar;
            Scrollbar verticalScrollbar = scrollRect.verticalScrollbar;
            var onValueChanged = scrollRect.onValueChanged;

            DestroyImmediate(scrollRect);
            CustomScrollRect customScrollRect = gameObject.AddComponent<CustomScrollRect>();

            customScrollRect.content = content;
            customScrollRect.horizontal = horizontal;
            customScrollRect.vertical = vertical;
            customScrollRect.movementType = movementType;
            customScrollRect.elasticity = elasticity;
            customScrollRect.inertia = inertia;
            customScrollRect.decelerationRate = decelerationRate;
            customScrollRect.viewport = viewport;
            customScrollRect.horizontalScrollbar = horizontalScrollbar;
            customScrollRect.verticalScrollbar = verticalScrollbar;
            customScrollRect.onValueChanged = onValueChanged;
        }

        private SerializedProperty preventScroll;

        protected override void OnEnable() {
            base.OnEnable();

            preventScroll = serializedObject.FindProperty("preventScroll");
        }

        public override void OnInspectorGUI() {
            serializedObject.Update();
            EditorGUILayout.PropertyField(preventScroll);
            serializedObject.ApplyModifiedProperties();

            base.OnInspectorGUI();
        }

    }
#endif

}